package stark.app.frame.compress;
/**
 *  https://github.com/RuiXiuDe/Compress
 */

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.rratchet.android.compress.CompressHelper;
import com.stark.doc.selector.DefDocSelActivity;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import stark.app.R;
import stark.common.basic.constant.Extra;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.utils.PermissionUtil;

public class FileCompressActivity extends AppCompatActivity {

    public int FILE_SELECT_CODE_UNZIP = 0x001;
    public int FILE_SEL_ZIP = 2;
    public int FILE_SELECT_CODE_ZIP = 0x003;
    private AlertDialog alertDialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if (alertDialog != null && !alertDialog.isShowing()) {
                    alertDialog.show();
                }
            } else {
                if (alertDialog != null && alertDialog.isShowing()) {
                    alertDialog.dismiss();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_compress);
        findViewById(R.id.unzip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.with(FileCompressActivity.this)
                        .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request(granted -> {
                            if (granted) { // Always true pre-M
                                Log.e(TAG, "onClick: unzip");
                                CompressUtils.showFileChooser(FileCompressActivity.this, FILE_SELECT_CODE_UNZIP);
                            } else {
                            }
                        });
            }
        });
        findViewById(R.id.zip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.with(FileCompressActivity.this)
                        .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request(granted -> {
                            if (granted) {
                                CompressUtils.showFileChooser(FileCompressActivity.this, FILE_SELECT_CODE_ZIP);
                            } else {
                            }
                        });
            }
        });
        findViewById(R.id.btnSelZip).setOnClickListener(v -> {
            DefDocSelActivity.selCompressFile(this, FILE_SEL_ZIP);
        });
        alertDialog = new AlertDialog.Builder(this).setMessage("正在操作，请稍等...").setCancelable(false).create();
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, final Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if ((requestCode == FILE_SELECT_CODE_UNZIP || requestCode == FILE_SELECT_CODE_ZIP)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(0);
                    Uri uri = data.getData();
                    String path = CompressUtils.getPath(FileCompressActivity.this, uri);
                    if (path == null) {
                        Log.e(TAG, "run: path is null");
                        return;
                    }
                    String name = new File(path).getName();
                    name = name.substring(0, name.lastIndexOf("."));
                    try {
                        if (requestCode == FILE_SELECT_CODE_UNZIP) {

                            String output = new File(getExternalCacheDir(), name).getAbsolutePath();
                            CompressHelper.extract(path, output);


                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(FileCompressActivity.this, "解压文件目录：" + output + path, Toast.LENGTH_SHORT).show();

                                }
                            });

                            Log.e(TAG, "run: 解压" + output);
                        } else {
                            name += ".rar";
                            Log.e(TAG, "run: " + name);
                            String finalName = name;
                            String dirRar = "压缩文件目录：" + CompressHelper.compressRarFile(path, new File(getExternalCacheDir(), finalName).getAbsolutePath());
                            Log.e(TAG, "run: "+dirRar );
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    try {

                                        Toast.makeText(FileCompressActivity.this,dirRar, Toast.LENGTH_SHORT).show();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }
                            });

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    handler.sendEmptyMessage(1);
                }
            }).start();

        }

        if (requestCode == FILE_SEL_ZIP) {
            MediaInfo mediaInfo = (MediaInfo) data.getSerializableExtra(Extra.DATA);
            ToastUtils.showShort(mediaInfo.toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private static final String TAG = "FileCompressActivity";
}
